package spark_from_scratch.basic

import org.apache.spark.{SparkConf, SparkContext}

import scala.math.random

/**
 * @author andrew
 * @email zengjunjie1026@163.com
 * @date 2020/9/3 3:26 下午
 * @version 1.0
 */
object SparkPi {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("Spark Pi ").setMaster("local[4]")
    val spark = new SparkContext(conf)
    val slices = if (args.length > 0) args(0).toInt else 2
    println("slices:\n"+slices)
    println("args.length:\n"+args.length)
    val n = math.min(1000000000000L * slices, Int.MaxValue).toInt // avoid overflow
    val count = spark.parallelize(1 until n, slices).map { i =>
      val x = random * 2 - 1
      val y = random * 2 - 1
      if (x*x + y*y < 1) 1 else 0
    }.reduce(_ + _)
    println("Pi is roughly " + 4.0 * count / n)
    spark.stop()
  }
}